<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Apply as ModelApply;
use app\common\model\User;

/**
 * 晋升申请
 */
class Apply extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 提交申请
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="area_id", type="integer", required=true, sample="3", description="区域ID")
     * @ApiParams (name="area_ids", type="integer", required=true, sample="1,2,3", description="省市区ID 逗号分隔")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function add(){
        $user = $this->auth->getUser();
        $has = ModelApply::where('user_id',$user->id)->where('status','0')->find();
        if($has){
            $this->error('已有审核中的申请,请勿重复提交');
        }
        $data = $this->request->post();
        if($user->level_id<6){
            //条件判断
            $num = config('site.area_agent_levelup');
            $sons = User::where('pid',$user->id)->column('id');
            $flag = false;
            
            foreach ($sons as $key => $id) {
                $has = User::where('find_in_set(:id,team_tag)',['id'=>$id])->where('level_id',5)->count();
                if($has){
                    $num--;
                }
                if($num<=0){
                    $flag = true;
                    break;
                }
            }
            if(!$flag){
                $this->error('未满足申请条件');
            }

            $data['level_id'] = 6;
        }elseif($user->level_id==6){
            $num = config('site.city_agent_levelup');
            $sons = User::where('pid',$user->id)->column('id');
            $flag = false;
            
            foreach ($sons as $key => $id) {
                $has = User::where('find_in_set(:id,team_tag)',['id'=>$id])->where('level_id',6)->count();
                if($has){
                    $num--;
                }
                if($num<=0){
                    $flag = true;
                    break;
                }
            }
            if(!$flag){
                $this->error('未满足申请条件');
            }

            //区域
            $data['level_id'] = 7;

        }else{
            $this->error('等级不可申请');
        }

        $data['user_id']= $user->id;
        $area_has = User::where('agent_area_id',$data['area_id'])->find();
        if($area_has){
            $this->error('该区域已有代理');
        }
        $apply = new ModelApply();
        $apply->allowField(true)->save($data);
        $this->responseMsg(0);
        // if()
    }
}